package com.rayo.accesscontrollercopy.model.service;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.rayo.accesscontrollercopy.config.GlobalVariables;
import com.rayo.accesscontrollercopy.model.biz.INetworkBiz;
import com.rayo.accesscontrollercopy.model.biz.NetworkBiz;
import com.rayo.accesscontrollercopy.model.network.ApiCmd;
import com.rayo.accesscontrollercopy.model.network.WebSocketHelp;
import com.rayo.accesscontrollercopy.model.network.bean.BaseApi;
import com.rayo.accesscontrollercopy.model.network.bean.ConnectApi;


/**
 * Created by yanghaojie on 2017/3/19.
 */

public class NetWorkHeartThread implements Runnable {
    private boolean isPause = true;
    private boolean isStop = true;
    private long time;
    private long send_time = System.currentTimeMillis();
    private INetworkBiz mINetworkBiz;

    public NetWorkHeartThread(NetworkBiz networkBiz) {
        this.mINetworkBiz = networkBiz;
    }



    @Override
    public void run() {
        isPause = false;
        isStop = false;
        long t = 15 * 1000;
        synchronized (this) {
            while (!isStop) {
                time = System.currentTimeMillis();

                if (!isPause && (time - send_time > t)) {
                    send_time = System.currentTimeMillis();
                    if (!WebSocketHelp.getmInstance().isConnect()) {
                        WebSocketHelp.getmInstance().connect();
                        Log.e("30s","30s");
                    } else {


                        if (GlobalVariables.getInstance().getmSiteData()==null||GlobalVariables.getInstance().getmSiteData().getLockid()==0) {

                            WebSocketHelp.getmInstance().sendMessage(JSON.toJSONString(new BaseApi(ApiCmd.CONNECT, GlobalVariables.getInstance().getmSiteData().getSite(), new ConnectApi())));
                        }
                        else {

                            mINetworkBiz.postEvents();
                            mINetworkBiz.updateDb(String.valueOf(GlobalVariables.getInstance().getmSiteData().getLockid()));
                        }
                    }
                }
            }
        }
    }

    public void setSend_time() {
        this.send_time = System.currentTimeMillis();
    }

    public void onPause() {
        isPause = true;
    }

    public void onResume() {
        isPause = false;
    }

    public void onDestory() {
        isStop = true;
    }
}
